<template>
  <div class="customer-container">
    <a-card class="customer-card">
      <template #title>
        <div class="card-header">
          <span>客户管理</span>
          <div class="header-buttons">
            <a-button type="primary" @click="showAddModal">
              <template #icon><plus-outlined /></template>
              添加客户
            </a-button>
          </div>
        </div>
      </template>

      <!-- 查询表单 -->
      <a-form :model="searchForm" layout="inline" class="query-form">
        <a-form-item label="客户名称">
          <a-input v-model:value="searchForm.name" placeholder="请输入客户名称" allowClear />
        </a-form-item>
        <a-form-item label="客户阶段">
          <a-select v-model:value="searchForm.stage" placeholder="请选择客户阶段" allowClear>
            <a-select-option value="POTENTIAL">潜在客户</a-select-option>
            <a-select-option value="INTENTION">意向客户</a-select-option>
            <a-select-option value="DEAL">成交客户</a-select-option>
            <a-select-option value="LOST">流失客户</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="客户状态">
          <a-select v-model:value="searchForm.status" placeholder="请选择客户状态" allowClear>
            <a-select-option value="ACTIVE">正常</a-select-option>
            <a-select-option value="INACTIVE">停用</a-select-option>
            <a-select-option value="PENDING">待审核</a-select-option>
            <a-select-option value="APPROVED">已审核</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <a-table
        :columns="columns"
        :data-source="customers"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleEdit(record as Customer)">编辑</a-button>
              <a-button
                v-if="record.status === 'PENDING'"
                type="link"
                @click="handleApprove(record as Customer)"
              >
                审核
              </a-button>
              <a-button type="link" @click="handleDelete(record as Customer)">删除</a-button>
              <a-button type="link" @click="handleDepartment(record as Customer)"
                >关联部门</a-button
              >
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:open="modalVisible"
      :title="modalTitle"
      @cancel="handleModalCancel"
      width="800px"
      :maskClosable="false"
      :footer="null"
    >
      <div v-if="modalVisible">
        <customer-form
          :customer="currentCustomer"
          @submit="handleFormSubmit"
          @cancel="handleModalCancel"
        />
      </div>
    </a-modal>

    <a-modal
      v-model:open="approveModalVisible"
      title="审核客户"
      @ok="handleApproveSubmit"
      @cancel="handleApproveCancel"
      :maskClosable="false"
    >
      <a-form :model="approveForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="审核结果" name="approved">
          <a-radio-group v-model:value="approveForm.approved">
            <a-radio :value="true">通过</a-radio>
            <a-radio :value="false">拒绝</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="审核意见" name="comment">
          <a-textarea v-model:value="approveForm.comment" :rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>

    <DepartmentDialog
      v-if="selectedCustomer"
      ref="departmentDialogRef"
      :customer-id="selectedCustomer.id"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import {
  Button as AButton,
  Table as ATable,
  Modal as AModal,
  Space as ASpace,
  Tag as ATag,
  Popconfirm as APopconfirm,
  Form as AForm,
  FormItem as AFormItem,
  Input as AInput,
  Select as ASelect,
  SelectOption as ASelectOption,
  Card as ACard,
  message,
  type TablePaginationConfig,
} from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import CustomerForm from './CustomerForm.vue'
import {
  getCustomers,
  createCustomer,
  updateCustomer,
  deleteCustomer,
  approveCustomer,
} from '@/api/customer'
import DepartmentDialog from './DepartmentDialog.vue'
import axios from 'axios'

interface Customer {
  id: number
  name: string
  stage: string
  source: string
  status: string
  salesId?: number
  serviceId?: number
  visitAddress?: string
  registerAddress?: string
  createdAt: string
  updatedAt: string
  departments?: Array<{ id: number }>
  sales?: { id: number; name: string }
  service?: { id: number; name: string }
}

interface SearchForm {
  name?: string
  stage?: string
  status?: string
}

interface ApproveForm {
  approved: boolean
  comment: string
}

const loading = ref(false)
const customers = ref<Customer[]>([])
const modalVisible = ref(false)
const modalTitle = ref('')
const currentCustomer = ref<Customer | null>(null)
const approveModalVisible = ref(false)
const approveForm = ref<ApproveForm>({
  approved: true,
  comment: '',
})

const searchForm = reactive<SearchForm>({
  name: '',
  stage: undefined,
  status: undefined,
})

const columns = [
  {
    title: '客户名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '客户阶段',
    dataIndex: 'stage',
    key: 'stage',
    customRender: ({ text }: { text: Customer['stage'] }) => getStageText(text),
  },
  {
    title: '客户来源',
    dataIndex: 'source',
    key: 'source',
    customRender: ({ text }: { text: Customer['source'] }) => getSourceText(text),
  },
  {
    title: '销售',
    dataIndex: ['sales', 'name'],
    key: 'sales',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
]

const pagination = ref<{
  current: number
  pageSize: number
  total: number
}>({
  current: 1,
  pageSize: 10,
  total: 0,
})

const departmentDialogRef = ref()
const selectedCustomer = ref<Customer | null>(null)

const getStatusColor = (status: Customer['status']) => {
  const colors: Record<Customer['status'], string> = {
    ACTIVE: 'green',
    INACTIVE: 'orange',
    DELETED: 'red',
    APPROVED: 'green',
    PENDING: 'orange',
  }
  return colors[status] || 'default'
}

const getStatusText = (status: Customer['status']) => {
  const texts: Record<Customer['status'], string> = {
    ACTIVE: '正常',
    INACTIVE: '停用',
    DELETED: '已删除',
    APPROVED: '已审核',
    PENDING: '待审核',
  }
  return texts[status] || status
}

const getStageText = (stage: Customer['stage']) => {
  const texts: Record<Customer['stage'], string> = {
    LEAD: '潜在客户',
    QUALIFIED: '已确认需求',
    PROPOSAL: '方案报价',
    NEGOTIATION: '商务谈判',
    CONTRACT: '合同签订',
    IMPLEMENTATION: '实施交付',
    MAINTENANCE: '售后维护',
    LOST: '已流失',
  }
  return texts[stage] || stage
}

const getSourceText = (source: Customer['source']) => {
  const texts: Record<Customer['source'], string> = {
    TELEMARKETING: '电话营销',
    WEBSITE: '官网',
    SOCIAL_MEDIA: '社交媒体',
    REFERRAL: '客户推荐',
    EXHIBITION: '展会',
    SEARCH_ENGINE: '搜索引擎',
    EMAIL_MARKETING: '邮件营销',
    PARTNER: '合作伙伴',
    OTHER: '其他',
  }
  return texts[source] || source
}

const loadCustomers = async () => {
  loading.value = true
  try {
    const response = await getCustomers({
      page: pagination.value.current - 1,
      size: pagination.value.pageSize,
      ...searchForm,
    })
    console.log('加载的客户数据:', response.data)
    customers.value = response.data.content
    pagination.value.total = response.data.totalElements
  } catch (error) {
    console.error('加载客户列表失败:', error)
    message.error('加载客户列表失败')
  } finally {
    loading.value = false
  }
}

const handleTableChange = (
  pag: TablePaginationConfig,
  filters: Record<string, any>,
  sorter: any,
) => {
  if (pag.current && pag.pageSize) {
    pagination.value = {
      current: pag.current,
      pageSize: pag.pageSize,
      total: pag.total || 0,
    }
    loadCustomers()
  }
}

const handleSearch = () => {
  pagination.value.current = 1
  loadCustomers()
}

const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    stage: undefined,
    status: undefined,
  })
  pagination.value.current = 1
  loadCustomers()
}

const showAddModal = () => {
  modalTitle.value = '添加客户'
  currentCustomer.value = null
  modalVisible.value = true
}

const handleEdit = (record: Customer) => {
  console.log('点击编辑按钮')
  console.log('当前记录:', record)
  showEditModal(record)
}

const showEditModal = (record: Customer) => {
  console.log('=== 开始编辑客户流程 ===')
  console.log('1. 原始客户数据:', record)
  modalTitle.value = '编辑客户'
  currentCustomer.value = {
    ...record,
    departments: record.departments?.map((dept) => ({ id: dept.id })) || [],
    salesId: record.sales?.id,
    serviceId: record.service?.id,
  }
  console.log('2. 处理后的客户数据:', currentCustomer.value)
  console.log('3. 设置 modalVisible 为 true')
  modalVisible.value = true
  console.log('4. modalVisible 当前值:', modalVisible.value)
  console.log('5. currentCustomer 当前值:', currentCustomer.value)
}

const handleFormSubmit = async (formData: any) => {
  console.log('提交的表单数据:', formData)
  try {
    if (currentCustomer.value) {
      await updateCustomer(currentCustomer.value.id, formData)
      // 记录更新日志
      await axios.post('/api/logs', {
        action: 'UPDATE_CUSTOMER',
        description: `更新客户：${formData.name}`,
      })
      message.success('更新客户成功')
    } else {
      await createCustomer(formData)
      // 记录创建日志
      await axios.post('/api/logs', {
        action: 'CREATE_CUSTOMER',
        description: `创建客户：${formData.name}`,
      })
      message.success('添加客户成功')
    }
    modalVisible.value = false
    loadCustomers()
  } catch (error) {
    console.error('保存客户失败:', error)
    message.error('保存客户失败')
  }
}

const handleModalCancel = () => {
  console.log('=== 关闭模态框 ===')
  console.log('关闭前的 modalVisible:', modalVisible.value)
  modalVisible.value = false
  currentCustomer.value = null
  console.log('关闭后的 modalVisible:', modalVisible.value)
}

const handleDelete = async (record: Customer) => {
  try {
    await deleteCustomer(record.id)
    // 记录删除日志
    await axios.post('/api/logs', {
      action: 'DELETE_CUSTOMER',
      description: `删除客户：${record.name}`,
    })
    message.success('删除客户成功')
    loadCustomers()
  } catch (error) {
    message.error('删除客户失败')
  }
}

const handleApprove = (record: Customer) => {
  currentCustomer.value = record
  approveForm.value = {
    approved: true,
    comment: '',
  }
  approveModalVisible.value = true
}

const handleApproveSubmit = async () => {
  if (!currentCustomer.value) return

  try {
    await approveCustomer(currentCustomer.value.id, {
      approved: approveForm.value.approved,
      comment: approveForm.value.comment,
    })
    // 记录审核日志
    await axios.post('/api/logs', {
      action: 'APPROVE_CUSTOMER',
      description: `审核客户：${currentCustomer.value.name}，结果：${approveForm.value.approved ? '通过' : '拒绝'}`,
    })
    message.success('审核操作成功')
    approveModalVisible.value = false
    loadCustomers()
  } catch (error) {
    message.error('审核操作失败')
  }
}

const handleApproveCancel = () => {
  approveModalVisible.value = false
  currentCustomer.value = null
  approveForm.value = {
    approved: true,
    comment: '',
  }
}

const handleDepartment = (record: Customer) => {
  selectedCustomer.value = record
  nextTick(() => {
    departmentDialogRef.value?.show()
  })
}

onMounted(() => {
  loadCustomers()
  // 记录访问日志
  axios.post('/api/logs', {
    action: 'ACCESS_PAGE',
    description: '访问客户管理页面',
  })
})
</script>

<style scoped>
.customer-container {
  padding: 16px;
}

.customer-card {
  background: #fff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 8px;
}

.query-form {
  margin-bottom: 16px;
}

.query-form :deep(.ant-form-item) {
  margin-bottom: 16px;
  margin-right: 16px;
}

.query-form :deep(.ant-form-item:last-child) {
  margin-right: 0;
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 500;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background: #f5f5f5;
}

:deep(.ant-form-item-label) {
  min-width: 80px;
  text-align: right;
}

:deep(.ant-form-item-control) {
  flex: 1;
}
</style>
